<template>
  <div class="base-single-form -mt-25px">


    <!-- 表格 -->
    <CustomTable
      :table-columns="realColumns"
      :table-data="realTableData"
      :page="page"
      :show-selection="true"
      height="700"
      @update:page="(val) => $emit('update:page', val)"
      @selection-change="handleSelectionChange"
      @sort-change="handleSortChange"
      @row-dblclick="handleRowDbClick"
      @cell-click="handleCellClick"
      :row-class-name="myRowClass"
      >
            <template #toolbar-left>
           <!-- 按钮组 -->
    <ActionButtonGroup
      :show-search="showSearch"
      :show-add="showAdd"
      :show-edit="showEdit"
      :show-preview="showPreview"
      :show-delete="showDelete"
      :disabled-add="disabledAdd"
      :disabled-edit="localDisabledEdit"
      :disabled-delete="localDisabledDelete"
      :disabled-preview="localDisabledEdit"
      @add="handleAdd"
      @edit="handleEdit"
      @preview="handlePreview"
      @delete="handleDelete"
      @search="handleSearch"
      >

    </ActionButtonGroup>
    
    <slot name="toolbarExtra" />
 
      </template>
      </CustomTable>


    <!-- 编辑弹窗 -->
      <!--fullscreen-->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="80%"
      top="5vh"
      :before-close="handleClose"
      :fullscreen="isFullscreen"
      :show-close="false"
    >
        <template #header="{ close, titleId, titleClass }">
      <div flex items-center justify-between>
        <h6 :id="titleId" :class="titleClass">{{ dialogTitle }}</h6>
        <div ml-auto flex items-center gap-2>
          <el-icon cursor-pointer text-18px @click="isFullscreen = !isFullscreen">
            <FullScreen v-if="!isFullscreen" />
            <CopyDocument v-else />   <!-- 还原图标 -->
          </el-icon>
                
          <el-icon 
            cursor-pointer text-18px
            @click="close"
          >
            <CircleClose />
          </el-icon>
        </div>
      </div>
    </template>

    
      <FormComponent
        ref="formComponentRef"
        :fields="realFormFields"
        :data="formData"
        @update:data="(val) => $emit('update:formData', val)"
      />
      <template #footer>
        <el-button @click="handleCancel">{{ $t('btn.cancel') }}</el-button>
        <el-button type="primary" :disabled="disabledSave" @click="handleSave">{{ $t('btn.save') }}</el-button>
      </template>
    </el-dialog>

    <!-- 查询抽屉 -->
    <DynamicSearchDrawer
      v-model="searchDrawer"
      :data="searchFormData"                     
      @update:data="(val) => emit('update:searchFormData', val)"
      :fields="realSearchFields"
      direction="ltr"
      size="420px"
      append-to-body
      destroy-on-close
      @search="handleQuery"
    />
  </div>
</template>

<script lang="ts" setup>
import {
  ref,
  computed,
  watch,
  nextTick,
  PropType,
  onMounted
} from 'vue'
import { useI18n } from 'vue-i18n'
import { msgError } from '@/utils/msg'
import { doFormSave, remove } from '@/utils/apiHelper'
import { getFields, query } from '@/utils/apiHelper'
import { createQueryParams } from '@/api/types'
import type { PageInfo } from '@/types'

import { buildValidator } from '@/utils/buildValidator'

import ActionButtonGroup from '@/components/ActionBtnHdrCont.vue'
import CustomTable from '@/components/ActionVxeGridCont.vue'
import FormComponent from '@/components/ActionFormCont.vue'
import DynamicSearchDrawer from '@/components/ActionSearchCont.vue'
import defaultConfig from '@config'

/* ----------------- props & emit ----------------- */
const props = defineProps({
  /* 按钮显隐 */
  // 是否显示搜索按钮
  showSearch: {
    type: Boolean,
    default: false,
  },

  // 是否显示新增按钮
  showAdd: {
    type: Boolean,
    default: false,
  },
  // 是否显示修改按钮
  showEdit: {
    type: Boolean,
    default: false,
  },
  // 是否显示预览按钮
  showPreview: {
    type: Boolean,
    default: true,
  },
  // 是否显示删除按钮
  showDelete: {
    type: Boolean,
    default: false,
  },
  /* 按钮禁用 */
  // 新增按钮是否禁用
  disabledAdd: { 
    type: Boolean, 
    default: false },
// 编辑按钮是否禁用
  disabledEdit: { 
    type: Boolean, 
    default: true },
    // 修改按钮是否禁用
  disabledPreview: { 
    type: Boolean, 
    default: true },
    // 删除按钮是否禁用
  disabledDelete: { 
    type: Boolean, 
    default: true },
    //  是否全屏
  isFullscreen:{
    type: Boolean, 
    default: false },

  /* 表格 */
  tableColumns: { type: Array, default: () => [] },
  tableData: { type: Array, default: () => [] },
  /* 分页 – 双向绑定 */
  page: { type: Object as PropType<PageInfo>,
          default: () => ({ currentPage: 1, 
            pageSize:defaultConfig.tablePageSize, 
            pageSizes: defaultConfig.tablePageSizes,
            total: 0 })
        },

  /* 表单 */
  formFields: { type: Array, default: () => [] },
  formData: { type: Object, required: true },

  /* 查询 */
  searchFields: { type: Array, default: () => [] },
  searchFormData: { type: Object, required: true },

  /* 弹窗标题 */
  titleAdd: { type: String, default: undefined },
  titleEdit: { type: String, default: undefined },

  /* 自动抓取开关 */
  autoFetchFields: { type: Boolean, default: true },
  autoFetchData: { type: Boolean, default: true },

  /* 查询附加参数 */
  listQuery: { type: Object, default: () => ({}) },
  /* 删除参数 */
  selectedId: { type: [String, Number], default: null },

  /* api */
  apiModule: { type: String, required: true },
  apiFields: { type: String, default: '' },

  /* 删除动作 */
  deleteAction: {
    type: String as PropType<'mark' | 'delete'>,
    default: 'mark',
    validator: (v: any) => ['mark', 'delete'].includes(v)
  }
})

const emit = defineEmits([
  'update:page',
  'update:formData',
  'update:disabledEdit',   
  'update:disabledDelete',
  'update:disabledPreview',
  'update:selectedId', 
  'update:searchFormData',
  'update:isFullscreen',
  'add',
  'edit',
  'delete',
  'search',
  'preview',
  'selection-change',
  'sort-change',
  'row-dblclick',
  'cell-click',
  'reload'
])

/* ----------------- i18n ----------------- */
const { t } = useI18n()

/* ----------------- 内部状态 ----------------- */
const dialogVisible = ref(false)
const searchDrawer = ref(false)
const formComponentRef = ref()
const selectedRows = ref<any[]>([])// 用于存储Table选中的数据
const localDisabledEdit = computed(() => selectedRows.value.length !== 1)
const localDisabledDelete = computed(() => selectedRows.value.length === 0)
const isFullscreen =  ref(props.isFullscreen)
const disabledSave=ref(false)

/* 自动抓取回来的数据 */
const innerColumns = ref<any[]>([])
const innerTableData = ref<any[]>([])
const innerFormFields = ref<any[]>([])
const innerSearchFields = ref<any[]>([])
const innerSelectedId = computed<string | number | null>({
  get: () => props.selectedId,
  set: val => emit('update:selectedId', val)
})
/* ---------- 字段、数据配置---------- */

/* ---------- 选中对象 ---------- */


/* ----------------- computed ----------------- */
const realTitleAdd = computed(() => props.titleAdd ?? t('btn.add'))
const realTitleEdit = computed(() => props.titleEdit ?? t('btn.edit'))
const dialogTitle = computed(() =>
  props.formData[props.formFields.find(f => f.key === 'id')?.key ?? 'id']
    ? realTitleEdit
    : realTitleAdd
)

/* 统一对外：优先用父层传入，没有就用内部抓的 */
const realColumns = computed(() => props.tableColumns.length ? props.tableColumns : innerColumns.value)
const realTableData = computed(() => props.tableData.length ? props.tableData : innerTableData.value)
const realFormFields = computed(() => props.formFields.length ? props.formFields : innerFormFields.value)
const realSearchFields = computed(() => props.searchFields.length ? props.searchFields : innerSearchFields.value)

// 合并基础条件 + 抽屉条件
function buildQuery(queryParam: Record<string, any> = {}) {
  // 1. 如果父层没给 listQuery，就按默认规则生成
  if (!props.listQuery || Object.keys(props.listQuery).length === 0) {
    return createQueryParams({
      data: { ...props.searchFormData, ...queryParam },
      sort: ['-create_date'],         // 默认排序

    })
  }
  console.log('searchFormData', props.searchFormData)
  // 2. 父层给了 listQuery，就沿用并合并搜索条件
  return {
    ...props.listQuery,
    data: {
      ...props.listQuery.data,
      ...props.searchFormData,
      ...queryParam
    }
  }
}


/* ----------------- 自动抓取 ----------------- */
const fetchFields = async () => {
  if (!props.autoFetchFields || !props.apiFields) return
  try {
    const res = await getFields(props.apiFields)
    innerColumns.value = res.data?.[props.apiFields] ?? []
    innerFormFields.value = innerColumns.value.map((f: any) => ({
      ...f,
      rules: f.Validation
        ? [{ validator: buildValidator({ ...f.Validation, fieldName: f.label }), trigger: f.Validation.trigger || 'blur' }]
        : undefined
    }))
    innerSearchFields.value = res.data?.[`${props.apiFields}_isFilter`] ?? []
  } catch (e: any) {
    msgError(`${t('message.apiException')}：${e.message}`)
    
  }
}

const fetchDetail   =  async (
  queryParam: Record<string, any> = {},
  id?: string | number
) => {
try {
const action = id != null ? 'selectById' : 'select'

    /* 三目运算符一次性赋值 */
    const sendParams: Record<string, any> | undefined =
      action === 'selectById'
        ? undefined
        : buildQuery(queryParam);

    const res = await query(props.apiModule, action, sendParams, id)
    
    return  (res.details ?? [])

}
catch (e: any) {
  msgError(`${t('message.apiException')}：${e.message}`)
   return  [] // 保证调用方拿到一致类型
    
}
}
const fetchTableData = async (
  queryParam: Record<string, any> = {},
  id?: string | number
) => {
  if (!props.autoFetchData) return

  try {
 

    const res = await fetchDetail(queryParam, id);

    innerTableData.value =res;
      

    emit('update:page', {
      ...props.page,
      total: res.total ?? ( res.details?.length ?? 0)
    })
  } catch (e: any) {
    msgError(`${t('message.apiException')}：${e.message}`)
  }
}


/* ----------------- 监听 ----------------- */
/* watch 之前先包一层 safe 访问 */
const unWrapPage = () => ({
  currentPage: props.page?.currentPage ?? 1,
  pageSize: props.page?.pageSize ?? 20
})

watch(
  [
    () => props.listQuery,
    () => unWrapPage().currentPage,
    () => unWrapPage().pageSize
  ],
  () => fetchTableData(),
  { immediate: true },
  
)
watch(
  () => props.searchFormData,
  val => console.log('子层收到 searchFormData', val),
  { immediate: true }
)


onMounted(() => fetchFields())

/* ----------------- 事件处理 ----------------- */
function handleAdd() {
  emit('add')
  dialogVisible.value = true
  disabledSave.value=false
}

async function openDialogForRow(
  mode: 'edit' | 'preview'   
) {
  if (selectedRows.value.length !== 1) {
    msgError(t(selectedRows.value.length ? 'table.selectedMax' : 'table.noSelected', { max: 1 }))
    return
  }
  const { id } = selectedRows.value[0]
  if (!id) return msgError(t('message.noID'))

  /* 通过 fetchTableData 单条查询（会返回 [res.detail]） */
  const res=await fetchDetail({}, id)
  console.log('handleEdit', res)
  const row = res[0] // 单条已包装成数组第 0 项
  if (mode === 'edit') {
    emit('edit')
    disabledSave.value=false
  } else if (mode === 'preview') {
    emit('preview')
     disabledSave.value=true
  }              // 事件通知（可选）
  emit('update:formData', row)      // 关键：把数据写回 v-model
  
  dialogVisible.value = true

}
const handleEdit = async () => {
  
  openDialogForRow('edit')
}
const  handlePreview= async () =>  {
  openDialogForRow('preview')
}

const handleDelete = async () => {
  if (!selectedRows.value.length) {
    msgError(t('table.noSelected'))
    return
  }
  try {
    await remove(props.apiModule, props.deleteAction, selectedRows.value)
    /* 仅当数据由子组件托管时才自动刷新 */
    if (props.autoFetchData) await fetchTableData()
    emit('reload')
  } catch {}
}

function handleSearch() {
  emit('search')
  searchDrawer.value = true
}

function handleQuery(payload: any) {
  searchDrawer.value = false
  fetchTableData(payload) // 直接把查询条件带过去
}

function handleSelectionChange(rows: any[]) {
  console.log('handleSelectionChange', rows) 
  //emit('update:disabledEdit', rows.length !== 1);
 // emit('update:disabledDelete', rows.length === 0); 
 
  emit('update:selectedId', rows.length === 1 ? rows[0].id : null)   // 关键
  selectedRows.value = rows
  emit('selection-change', rows)
}

function handleSortChange(sort: any) {
  emit('sort-change', sort)
}

const handleCellClick  = (row, column, cell, $event ) => {
 
  emit('update:selectedId', row?.id ?? null)   // 关键
  emit('cell-click',  row, column, cell,  $event );
 
}
function handleRowDbClick(row: any) {
  emit('row-dblclick', row)
}

function handleCancel() {
  dialogVisible.value = false
}

function handleClose(done: () => void) {
  dialogVisible.value = false
  nextTick(done)
}

const handleSave = async () => {
  console.log('handleSave', formComponentRef.value)
  console.log('handleSave', props.formData)
  const latestData = formComponentRef.value?.$refs.formRef?.model ?? props.formData
  // const latestData = formComponentRef.value?.$refs.formRef?.model 
  console.log('handleSave', latestData)
  const result = await doFormSave({
    module: props.apiModule,
    formData: latestData,
    formRef: formComponentRef.value?.$refs.formRef
  })
  if (result.success) {
    if (result.data) emit('update:formData', result.data)
    dialogVisible.value = false
    /* 仅当数据由子组件托管时才自动刷新 */
    if (props.autoFetchData) await fetchTableData()
    emit('reload')
  }
}

/* ---------- 表格操作.表格式化--------- */ 
function myRowClass({ row, rowIndex }) {   
  // ① 选中高亮（优先级最高）
 
  if (row.id === innerSelectedId.value) {
    return 'bg-blue-100 border-l-4 border-blue-500'
  }
    // ② 业务状态色
  const status = row.parent_id === '0' ? 'row-success' : 'row-gray-50'
  // ③ 斑马纹
  const stripe = rowIndex % 2 === 0 ?  'row-white':  'row-gray-50'

  return `${status} ${stripe}`.trim()
}



/* 暴露给父组件手动刷新数据 */
defineExpose({ reload: fetchTableData })
</script>
